var chain = require("./requestChain");
var cheerio = require("cheerio");
var _ = require("underscore");

/**
 *  main logic flow is : i-view->sso-> i-view
 *  list following are i-view urls
 *  @description : invoke like this,
 *      var connector = require('./iview-connector');
 *      connector.setAccount('name','pwd');
 *      connector.requestData(requestOption);
 *      requestOption is optional, attributes including: url,option,method,next,filter, refer to step1->step7
 * */
var authStr = "Basic ";

 var sso_url = "https://ssoidp.oocl.com/idp/2w9UL/resumeSAML11/idp/startSSO.ping";
var sso_login = "http://ssoidp.oocl.com/idp/startSSO.ping?PartnerSpId=OOCL:SP:SAML1&IdpAdapterId=" +
    "MSADAdapter&TargetResource=http%3A%2F%2Fhklxdv60%3A1234%2Fiview%2Flogin.jsp%3Flogonas%3D1";

var iview_host = "http://hln2058p:1234/iview";
var iview_url = "http://hln2058p:1234/iview/login.jsp?logonas=1";
var iview_out_url = "http://hln2058p:1234/iview/logout.jsp?logonas=1";

var main_frame_url = "http://hln2058p:1234/iview/servlet/MainMenu";

/* request options */
var clearAuth_step1 = {
        url: iview_out_url,
        option: {},
        method: 'GET',
        filter: function () {
            console.log('step 1 complete...');
        }
    },

    requestLogin_step2 = {
        url: iview_url,
        option: {},
        method: 'GET',
        filter: function () {
            console.log('step 2 complete...');
        }
    },

    ssoLoginPage_step3 = {
        url: sso_url,
        method: 'GET',
        option: {},
        filter: function () {
            console.log('step 3 complete...');
        }
    },

    ssoPostAuth_step4 = {
        url: sso_login,
        method: 'POST',
        option: {
            headers: {
                "Authorization": authStr
            }
        },
        filter: function (err, res, body, next) {
            console.log('step 4 complete...');
            next.url = res.headers.location;
        }
    },

    getPrivateToken_step5 = {
        url: null,
        method: 'GET',
        option: {
            headers: {
                "Authorization": authStr
            }
        },
        filter: function (err, res, body, next) {
            var $ = cheerio.load(res.body);
            var token = $("input").val();
            var target = $("input[name='TARGET']").val();
            var url = $("form").attr("action");
            next.url = url;
            next.option.form = {TARGET: target, SAMLResponse: token};
            console.log('step 5 complete...');
        }
    },

    postOpenToken_step6 = {
        url: null,
        method: 'POST',
        option: {
            headers: {
                "Authorization": authStr
            }
        },
        filter: function (err, res, body, next) {
            var $ = cheerio.load(body);
            next.option.form = {opentoken: $("input").val()}
            chain.addCookie(next, "USER_ID=yangjo", iview_host);
            chain.addCookie(next, "USER_NAME=" + $("input").val(), iview_host);
            console.log('step 6 complete...');
        }
    },

    postIviewToken_step7 = {
        url: iview_url,
        method: "POST",
        option: {},
        filter: function () {
            console.log('step 7 complete...');
        }
    },

    getIviewMainPage_step8 = {
        url: main_frame_url,
        method: 'GET',
        option: {},
        next: null,
        filter: function (err, res, body) {
            console.log('step 8 complete...');
            console.log(body);
            console.log('basic main frame data, if you can see <li>s means success');
        }
    };

var setAccount = function (username, password) {
    var nameAndPwd = new Buffer(username + ':' + password);
    var base = nameAndPwd.toString('base64');
    authStr += base;
    ssoPostAuth_step4.option.headers.Authorization = authStr;
    getPrivateToken_step5.option.headers.Authorization = authStr;
    postOpenToken_step6.option.headers.Authorization = authStr;
};

/**
 *  set your i-view account
 *  @param : username :password
 * */
exports.setAccount = setAccount;

/* build linked list */
clearAuth_step1.next = requestLogin_step2;
requestLogin_step2.next = ssoLoginPage_step3;
ssoLoginPage_step3.next = ssoPostAuth_step4;
ssoPostAuth_step4.next = getPrivateToken_step5;
getPrivateToken_step5.next = postOpenToken_step6;
postOpenToken_step6.next = postIviewToken_step7;
postIviewToken_step7.next = getIviewMainPage_step8;

var requestData = function (requestOption) {
    if (authStr != "Basic ") {
        if (!!requestOption) {
            getIviewMainPage_step8.next = requestOption;
            chain.startChain(clearAuth_step1);
        } else {
            chain.startChain(clearAuth_step1);
        }
    } else {
        console.log("Plz set your account first");
    }
};
exports.requestData = requestData;